package com.toutiao.vssue

import java.util.concurrent.LinkedBlockingQueue

import akka.actor.ActorSystem
import org.apache.log4j.Logger

import scala.concurrent.duration._
import scalaj.http._

class IDGetter(uri:String) {
  
  val cacheSize = 8192
  val interval:FiniteDuration = 30.milliseconds
  val sleepTime:FiniteDuration = 5.seconds
  
  private val log = Logger.getLogger(this.getClass.getName)
  
  private val queue = new LinkedBlockingQueue[Long](cacheSize)
  
  private val system = ActorSystem(this.getClass.getSimpleName)
  import system.dispatcher
  
  system.scheduler.schedule(Duration.Zero, interval) {
    try {
      val response: HttpResponse[String] = Http(uri).asString
      if (response.code == 200) 
        response.body.split(",").filter(_!="").foreach(x => queue.put(x.toLong)) 
      else 
        throw new RuntimeException(s"invalid status code ${response.body.toLong}")
    }
    catch {
      case t: Throwable =>
        log.error(s"IDGetter something wrong:" + "\n" +
          t + "\n" + t.getStackTrace.mkString("\n"))
        Thread.sleep(sleepTime.toMillis)
    }
  }
  
  def get:Long = queue.take
  
  def close = system.shutdown
  
}
